package cn.virens.library.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import cn.virens.library.R;


/**
 * Created by loioi on 2017/3/24.
 */

public class TextView extends AppCompatTextView {
    private int mDrawableWidth;
    private int mDrawableHeight;

    public TextView(Context context) {
        this(context, null);
    }

    public TextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        this._init(attrs, 0);
        this._initDrawableSize();
    }

    public TextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        this._init(attrs, defStyleAttr);
        this._initDrawableSize();
    }

    private void _init(AttributeSet attrs, int defStyleAttr) {
        final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextView, defStyleAttr, 0);

        this.mDrawableWidth = (int) a.getDimension(R.styleable.TextView_drawableWidth, 0F);
        this.mDrawableHeight = (int) a.getDimension(R.styleable.TextView_drawableHeight, 0F);

        a.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    private void _initDrawableSize() {
        Drawable[] drawables = getCompoundDrawables();

        if (drawables[0] != null) {
            int width = mDrawableWidth == 0 ? drawables[0].getMinimumWidth() : mDrawableWidth;
            int height = mDrawableHeight == 0 ? drawables[0].getMinimumHeight() : mDrawableHeight;

            drawables[0].setBounds(0, 0, width, height);
        }
        if (drawables[1] != null) {
            int width = mDrawableWidth == 0 ? drawables[1].getMinimumWidth() : mDrawableWidth;
            int height = mDrawableHeight == 0 ? drawables[1].getMinimumHeight() : mDrawableHeight;

            drawables[1].setBounds(0, 0, width, height);
        }
        if (drawables[2] != null) {
            int width = mDrawableWidth == 0 ? drawables[2].getMinimumWidth() : mDrawableWidth;
            int height = mDrawableHeight == 0 ? drawables[2].getMinimumHeight() : mDrawableHeight;

            drawables[2].setBounds(0, 0, width, height);
        }
        if (drawables[3] != null) {
            int width = mDrawableWidth == 0 ? drawables[3].getMinimumWidth() : mDrawableWidth;
            int height = mDrawableHeight == 0 ? drawables[3].getMinimumHeight() : mDrawableHeight;

            drawables[3].setBounds(0, 0, width, height);
        }

        setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);
    }
}
